<!--
 * iframe
 * @Author: xurenda <xurenda@qq.com>
 * @HomePage: https://xurenda.top
 * @Github: https://github.com/xurenda
 * @Date: 2019-11-14 14:14:50
 * @LastEditTime: 2019-11-15 14:59:52
 * @FilePath: \elegant-surf\src\components\search\Iframe.vue
 -->
<template>
<div id="iframes">
  <iframe
    v-for="(engine, key) in searchEngines"
    v-show="key === iframeKey"
    :key="key"
    :ref="key"
    :data-src="engine.url"
    :style="{ top: `-${engine.top}px`, height: `calc(100% + ${engine.top}px)` }"
    class="iframe"
    frameborder="0"
    target="_top"
  >
    您的浏览器不支持嵌入式框架，或者当前配置为不显示嵌入式框架。
  </iframe>
</div>
</template>

<script>
import { searchEngines } from '@/assets/js/data'
import EventBus, { CHANGE_ENGINE } from '@/assets/js/eventBus'

export default {
  name: 'app-iframe',
  data() {
    return {
      // 所有搜索引擎
      searchEngines,
      // 选中的搜索引擎的key
      iframeKey: this.$store.state.searchSetting.defaultEngine,
      // 搜索词
      query: this.$route.query.q
    }
  },
  watch: {
    // 当查询词变化时，重新获取内容
    $route(route) {
      this.query = route.query.q
      this.getIframeData(this.iframeKey)
    }
  },
  methods: {
    /**
     * @description: 当监听到点击“切换搜索引擎”时触发
     * @param {string} key 要切换到的搜索引擎的key
     * @return {void}
     */
    handleChangeEngine(key) {
      // 更改选中搜索引擎的key
      this.iframeKey = key
      // 获取选中搜索引擎的数据
      this.getIframeData(key)
    },

    /**
     * @description: 通过iframe的data-src获取src，实现iframe的懒加载
     * @param {string} key 要获取数据的搜索引擎iframe的key
     * @return {void}
     */
    getIframeData(key) {
      const iframe = this.$refs[key][0]
      if (iframe.src && iframe.dataset.query && iframe.dataset.query === this.query) return
      iframe.dataset.query = this.query
      iframe.src = iframe.dataset.src + this.query
    }
  },
  mounted() {
    // 监听点击“切换搜索引擎”
    EventBus.$on(CHANGE_ENGINE, this.handleChangeEngine)
    // 获取默认搜索引擎的数据
    this.getIframeData(this.iframeKey)
  }
}
</script>

<style lang="stylus">
#iframes
  width 100vw
  height 100vh
  iframe.iframe
    width 100%
    height 100%
    position absolute
    left 0
    top 0
</style>